import ioredis from 'ioredis'
import { REDIS_CONF } from '../config/db'
const { password, port, host } = REDIS_CONF
class Redis {
  client
  constructor() {
    //redis 6.0.0之前不支持username，而且一般也用不到多个用户名，所以设置完密码就可以使用了
    this.client = new ioredis({
      port,
      host,
      password
    })
    //监听redis的错误报告
    this.client.on('error', (err) => console.log(err))
  }
  //添加数据
  async set(key: string, value: any, time?: number | string) {
    //判断value值是否是对象类型
    if (typeof value === 'object') {
      value = JSON.stringify(value)
    }
    //time为过期时间，可选
    if (time) {
      await this.client.set(key, value, 'EX', time)
    } else {
      await this.client.set(key, value)
    }
  }
  async get(key: string) {
    const data = await this.client.get(key)

    return data
  }

  async delete(key: string) {
    await this.client.del(key)
  }
}

const redis = new Redis()
export default redis
